package cn.xspace.wnx.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;

import com.xspace.android.xafcommon.base.BaseActivity;
import com.xspace.android.xafcommon.base.PagerInfoView;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.ResourceUtils;
import com.xspace.android.xafcommon.view.sdlv.DragListView;
import com.xspace.android.xafcommon.view.sdlv.Menu;
import com.xspace.android.xafcommon.view.sdlv.MenuItem;
import com.xspace.android.xafcommon.view.sdlv.SlideAndDragListView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.xspace.app.view.TitleBar;
import cn.xspace.chatui.bean.MessageEntity;
import cn.xspace.library.util.BldNavigation;
import cn.xspace.library.util.MsgType;
import cn.xspace.wnx.R;
import cn.xspace.wnx.adapter.GroupManagerAdapter;
import cn.xspace.wnx.db.MessageRecordDao;
import cn.xspace.wnx.util.Navigator;
import de.greenrobot.event.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 群组助手
 */
public class GroupManagerActivity extends BaseActivity implements SlideAndDragListView.OnMenuItemClickListener,
        SlideAndDragListView.OnListItemClickListener, SlideAndDragListView.OnSlideListener, SlideAndDragListView
                .OnItemDeleteListener, SlideAndDragListView.OnListScrollListener, DragListView.OnDragListener {

    private static final String TAG = GroupManagerActivity.class.getSimpleName();

    protected TitleBar mTitleBar;
    private PagerInfoView mPagerInfoView;
    private Menu mMenu;
    private SlideAndDragListView<MessageEntity> mListView;
    private ArrayList<MessageEntity> mList;
    private GroupManagerAdapter groupManagerAdapter;
    private boolean isPause = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isPause) {
            try {
                refreshData();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        isPause = true;
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_group_manager);
    }

    @Override
    protected void initFindViewById() {
        mTitleBar = (TitleBar) findViewById(R.id.groups_manager_title_bar);
        mPagerInfoView = (PagerInfoView) findViewById(R.id.group_manager_pager_info);
        mListView = (SlideAndDragListView) findViewById(R.id.lv_groups_manager);
        initMenu();
        mListView.setMenu(mMenu);
    }

    /**
     * 侧滑弹出的菜单内的条目
     */
    private void initMenu() {
        mMenu = new Menu(true, true);
        mMenu.addItem(new MenuItem.Builder().setWidth((int) getResources().getDimension(R.dimen.space_49) + 40)
                .setBackground(ResourceUtils.getDrawable(R.drawable.selector_btn_delete))
                .setText(getString(R.string.delete)) //删除
                .setDirection(MenuItem.DIRECTION_RIGHT)
                .setTextColor(Color.WHITE)
                .setTextSize(14)
                .build());

    }

    @Override
    protected void initData() {
        mList = new ArrayList<>();
        groupManagerAdapter = new GroupManagerAdapter(this, mList);
        mListView.setAdapter(groupManagerAdapter);
        mListView.setOnDragListener(this, mList);
//        mListView.setPullLoadEnable(false);
//        mListView.setPullRefreshEnable(false);
        refreshData();
    }

    @Override
    protected void initEvent() {
        mTitleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mListView.setOnListItemClickListener(this);
        mListView.setOnSlideListener(this);
        mListView.setOnMenuItemClickListener(this);
//        mListView.setOnItemDeleteListener(this);
//        mListView.setOnListScrollListener(this);
    }

    private void refreshData() {
        registerSubscription(MessageRecordDao.getInstance().getiMessageData().getGroupList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<MessageEntity>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
//                        hideWaitDialog();
                    }

                    @Override
                    public void onNext(List<MessageEntity> list) {
//                        hideWaitDialog();
                        LogUtil.d(TAG, "wubaojie>>>listSize: " + list.size() + " list:" + list.toString());
                        mList.clear();
                        mList.addAll(list);
                        if (mList.size() == 0) {
                            mPagerInfoView.showPageEmpty(R.string.groups_manager_empty);
                        } else {
                            mPagerInfoView.hiddenPager();
                        }
                        groupManagerAdapter.notifyDataSetChanged();
                    }
                }));
    }

    public void onEventMainThread(Map<String, Object> map) {
        Object type = map.get(EventBusConstant.TYPE);
        if (type == null) {
            return;
        }
        if (EventBusConstant.HUANXIN_PUSH.equals(type)) {
            LogUtil.d(TAG, "wubaojie>>>onEventMainThread: 接收到新消息提醒");
            Object bean = map.get(EventBusConstant.HUANXIN_PUSH_BEAN);
            if (bean instanceof MessageEntity) {
                refreshData();
            }
        }
    }

    @Override
    public int onMenuItemClick(View v, int itemPosition, int buttonPosition, int direction) {
        switch (direction) {
            case MenuItem.DIRECTION_LEFT:
                switch (buttonPosition) {
                    case 0:
                        return Menu.ITEM_NOTHING;
                    case 1:
                        return Menu.ITEM_SCROLL_BACK;
                }
                break;
            case MenuItem.DIRECTION_RIGHT:
                switch (buttonPosition) {
                    case 0:
                        int position = itemPosition;
                        LogUtil.d(position + "");
                        MessageEntity deleteEntity = mList.get(position);
                        mList.remove(position);
                        groupManagerAdapter.notifyDataSetChanged();
                        if (deleteEntity.msg_type == MsgType.CHAT_CROUP.toNumber()) {
                            registerSubscription(MessageRecordDao.getInstance().getiMessageData().deleteGroupChat
                                    (deleteEntity.msg_group_id)
                                    .observeOn(Schedulers.io())
                                    .subscribe());
                        }
                        return Menu.ITEM_SCROLL_BACK;
                    case 1:
                        return Menu.ITEM_SCROLL_BACK;
                }
        }
        return Menu.ITEM_NOTHING;
    }

    @Override
    public void onListItemClick(View v, int position) {
        int index = position - mListView.getHeaderViewsCount();
//        if (mList.get(index).msg_type == MessageEntity.MsgType.CHAT_CROUP.toNumber()) { //不判断也可以,全是群组
        LogUtil.d(TAG, "wubaojie>>>onListItemClick: position :" + position + " index :" + index);
        MessageEntity messageEntity = mList.get(index);
        Bundle dataBundle = new Bundle();
        dataBundle.putString(BldNavigation.SENDER_ID, messageEntity.msg_group_id);
        dataBundle.putInt(BldNavigation.CHAT_TYPE, messageEntity.msg_type);
        dataBundle.putInt(BldNavigation.GROUP_TYPE, messageEntity.group_type);
        dataBundle.putString(BldNavigation.CHAT_NAME, messageEntity.msg_group_name);
        dataBundle.putString(BldNavigation.CHAT_SENDER_LOGO, "");
        Navigator.startChatActivity(mContext, dataBundle);
//        Bundle dataBundle = new Bundle();
//        dataBundle.putString(Navigator.SENDER_ID, group.group_id);
//        dataBundle.putInt(Navigator.CHAT_TYPE, MessageEntity.MsgType.CHAT_CROUP.toNumber());
//        dataBundle.putString(Navigator.CHAT_NAME, group.group_name);
//        dataBundle.putString(Navigator.CHAT_SENDER_LOGO, group.group_logo);
//        dataBundle.putInt(Navigator.GROUP_TYPE, mGroupTyp);
//        dataBundle.putSerializable(MsgForwardActivity.FORWARD_ENTITY, recordEntity);
//        Navigator.startChatActivity(mContext, dataBundle);
//        }
    }

    @Override
    public void onSlideOpen(View view, View parentView, int position, int direction) {

    }

    @Override
    public void onSlideClose(View view, View parentView, int position, int direction) {

    }

    @Override
    public void onItemDelete(View view, int position) {

    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }

    @Override
    public void onDragViewStart(int position) {

    }

    @Override
    public void onDragViewMoving(int position) {

    }

    @Override
    public void onDragViewDown(int position) {

    }
}
